package com.yonghui.springsecurityoauth2demo.config;

import com.yonghui.springsecurityoauth2demo.exception.OAuthServerAuthenticationEntryPoint;
import com.yonghui.springsecurityoauth2demo.exception.OAuthServerWebResponseExceptionTranslator;
import com.yonghui.springsecurityoauth2demo.filter.OAuthServerClientCredentialsTokenEndpointFilter;
import com.yonghui.springsecurityoauth2demo.service.CustomClientDetailsService;
import com.yonghui.springsecurityoauth2demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liyonghui
 * @description: 授权服务器
 * @date 2021/12/5 13:43
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    //    @Autowired
//    @Qualifier("redisTokenStore")
//    private TokenStore redisTokenStore;
    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore jwtTokenStore;
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;

    @Autowired
    private CustomClientDetailsService customClientDetailsService;

    @Autowired
    private OAuthServerAuthenticationEntryPoint authenticationEntryPoint;

    /**
     * @description: 使用密码模式所需配置
     * @author liyonghui
     * @date 2021/12/5 14:27
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {



        //配置JWT内容增强
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        tokenEnhancerChain.setTokenEnhancers(delegates);

        endpoints.exceptionTranslator(new OAuthServerWebResponseExceptionTranslator())//设置异常WebResponseExceptionTranslator，用于处理用户名，密码错误、授权类型不正确的异常
                .authenticationManager(authenticationManager).userDetailsService(userService)
//                .tokenStore(redisTokenStore);
                //配置存储令牌策略
                .tokenStore(jwtTokenStore)
                .reuseRefreshTokens(true)
                .accessTokenConverter(jwtAccessTokenConverter)
                .tokenEnhancer(tokenEnhancerChain)
                .authorizationCodeServices(authorizationCodeServices())
                //.pathMapping("/oauth/confirm_access", "/custom/confirm_access")
        ;
    }

    // @Bean
    // public CustomAuthorizationCodeServices authorizationCodeServices() {
    //     return new CustomAuthorizationCodeServices();
    // }

    @Bean
    public MyBatisAuthorizationCodeServices authorizationCodeServices() {
        return new MyBatisAuthorizationCodeServices();
    }

//     @Override
//     public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//         clients.inMemory()
//                 //配置client-id
//                 .withClient("admin")
//                 //配置client-secret
//                 .secret(passwordEncoder.encode("112233"))
//                 //配置访问token的有效期
// //                .accessTokenValiditySeconds(3600)
//                 //配置刷新令牌的有效期
//                 .refreshTokenValiditySeconds(864000)
//                 //配置redirect-url,用于授权成功后跳转
// //                .redirectUris("http://localhost:8081/login")
//                 .redirectUris("http://www.freeze721.com/success")
//                 //自动授权
// //                .autoApprove(true)
//                 .autoApprove(false)
//                 //配置申请的权限范围
//                 .scopes("all")
//                 //配置grant_type，表示授权类型（authorization_code：令牌模式）
// //                .authorizedGrantTypes("authorization_code")
//                 //授权类型-使用密码模式
//                 .authorizedGrantTypes("password","refresh_token","authorization_code")
//         ;
//     }


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(customClientDetailsService);


    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //自定义ClientCredentialsTokenEndpointFilter，用于处理客户端id，密码错误的异常
        OAuthServerClientCredentialsTokenEndpointFilter endpointFilter = new OAuthServerClientCredentialsTokenEndpointFilter(security,authenticationEntryPoint);
        endpointFilter.afterPropertiesSet();
        security.addTokenEndpointAuthenticationFilter(endpointFilter);

        //获取密钥需要身份认证,使用单点登录时必须配置
        security.tokenKeyAccess("isAuthenticated()");

    }
}
